
// function createComparisonFun(propertyName) {
//   return function(obj1, obj2){
//     let val1 = obj1[propertyName]
//     let val2 = obj2[propertyName]
//     if(val1 < val2) return -1
//     if(val1 > val2) return 1
//     return 0
//   }
// }
// const data = [
//   {name: 'Husky', age: 26},
//   {name: 'Caption', age: 29}
// ]
// console.log(JSON.stringify(data.sort(createComparisonFun('name'))))

// 斐波那契数列 Fibonacci
let count = 0
function fib(n) {
  count++
  if(n < 2) {
    return n
  }
  return fib(n-1) + fib(n-2)
}
fib(100) // count 177
console.log('count:', count)


// 优化斐波那契数列
// 在memo的数组中保存存储结果，存储结果可以隐藏在必包中
let countMemo = 0
const memoizer = function (memo, formula){
  const recur = function (n){
    countMemo++
    let result = memo[n]
    if(typeof result !== 'number'){
      result = formula(recur, n)
      memo[n] = result
    }
    return result
  }
  return recur
}
const fibMemo = memoizer([0,1], function(recur, n){
  return recur(n-1) + recur(n-2)
})
fibMemo(100) // countMemo -> 19
console.log('countMemo:', countMemo)

// 尾调用优化，使用两个嵌套函数，外部函数作为基础框架，内部函数执行递归
let tmpCount = 0
// 基础框架
function fib1 (n) {
  return fibTmp(0,1,n)
}
// 执行递归
function fibTmp(a,b,n){
  tmpCount++
  if(n === 0){
    return a
  }
  return fibTmp(b, b+a, n-1)
}
fib1(10) // tmpCount -> 11
console.log('tmpCount:', tmpCount)